
--[[
1服务的入口文件
2用户信息的服务
3在这个服务中可以拓展出玩家的各种功能
]]



local skynet = require("skynet")
local proto = require("network.proto")
---------------------------------------------------------
-- class
---------------------------------------------------------
local Service = class("Agent")

function Service:ctor(name)

    self.handler = new("agent.handler")
    self.client_pack = new("client_pack")
    self:register()
end

function Service:register()
    g.dispatch:register('start', handler(self, self.onStart))
    g.dispatch:register('close', handler(self, self.onClose))

end

function Service:gc()
    while true do
        g.sleep(60*100)
        collectgarbage "collect"
    end
end

--conn_info 连接的信息
function Service:onStart(conn_info)
    g.log:info("onStart agent", conn_info)
    g.conn_info = conn_info
    local nodefullname = g.getenv("nodefullname")  --在clusert.service里有设置
    g.nodefullname = nodefullname

    self.handler:registerUserPos() --向redis注册位置

    local fd = conn_info.fd
    --接管gate的client消息
    g.call(".gate", "forward", fd)
    skynet.register_protocol( {
        name = "client",
        id = skynet.PTYPE_CLIENT,
        unpack = function (msg, sz)
            return self.client_pack:unpack(msg, sz) --解包
        end,
        dispatch = function (_, _, proto_type, ...)
            skynet.ignoreret()	-- session is fd, don't call skynet.ret
            skynet.trace()
            local ok , res = xpcall(g.dispatch.dispatchMessage, g.handle_err, g.dispatch, nil, nil, ...)
            --local res = g.dispatch:dispatchMessage(nil, nil, ...)
            g.log:info("agent res:", res)
            if ok and res and next(res) then
                local name = res[1]
                if type(name) == "number" then
                    name = proto[name]
                end
                if name then
                    --消息回给client
                    self.client_pack:send(fd, name, res[2])
                end
            else
                g.log:error(res)
            end
        end
    })
    --定时gc一下
    g.fork(function()
        self:gc()
    end)
    print("111111112222")
    return true
end

function Service:onClose()
    print("onClose")
    return true
end


return Service